<template>
  <div class="publish-center">
    <!-- 内容区域 -->
    <div class="publish-content">
      <div class="tab-content-wrapper">
        <div class="tab-content">


          <!-- 视频上传区域 -->
          <div class="upload-section">
            <h3>视频</h3>
            <div class="upload-options">
              <el-button type="primary" @click="selectMaterial" class="upload-btn">
                <el-icon><Upload /></el-icon>
                选择视频
              </el-button>
            </div>
            
            <!-- 已上传文件列表 -->
            <div v-if="myform.fileList.length > 0" class="uploaded-files">
              <h4>已上传文件：</h4>
              <div class="file-list">
                <div v-for="(file, index) in myform.fileList" :key="index" class="file-item">
                  <el-link :href="file.url" target="_blank" type="primary">{{ file.name }}</el-link>
                  <span class="file-size">{{ (file.size / 1024 / 1024).toFixed(2) }}MB</span>
                  <el-button type="danger" size="small" @click="removeFile(tab, index)">删除</el-button>
                </div>
              </div>
            </div>
          </div>



          <!-- 素材库选择弹窗 -->
          <MaterialSelectDialog
            v-model="materialSelectVisible"
            @confirm="confirmMaterialSelection"
          />

          <!-- 账号选择 -->
          <div class="account-section">
            <h3>账号</h3>
            <div class="account-display">
              <div class="selected-accounts">
                <el-tag
                  v-for="(account, index) in myform.selectedAccounts"
                  :key="index"
                  closable
                  @close="removeAccount(tab, index)"
                  class="account-tag"
                >
                
                </el-tag>
              </div>
              <el-button type="primary"  plain  @click="openAccountDialog" class="select-account-btn" >
                选择账号
              </el-button>
            </div>
            <!-- 已选择账号 -->
            <div v-if="myform.accountList.length > 0" class="uploaded-files">
              <h4>已选择账号：</h4>
              <div class="file-list">
                <div v-for="(account, index) in myform.accountList" :key="index" class="file-item">
                  <span>{{ getPlatformNameApi(account.type) }}-----</span>
                  <span>{{ account.name }}</span>
                  
                  <el-button type="danger" size="small" @click="removeAccount(index)">删除</el-button>
                </div>
              </div>
            </div>
          </div>

          <!-- 账号选择弹窗 -->
          <AccountSelectDialog
            v-model="accountDialogVisible"
            @confirm="confirmAccountSelection"
          />

          <!-- 标题输入 -->
          <div class="title-section">
            <h3>标题</h3>
            <el-input
              v-model="myform.title"
              type="textarea"
              :rows="3"
              placeholder="请输入标题"
              maxlength="100"
              show-word-limit
              class="title-input"
            />
          </div>

          <!-- 话题输入 -->
          <div class="topic-section">
            <h3>话题</h3>
            <div class="topic-display">
              <div class="selected-topics">
                <el-tag
                  v-for="(topic, index) in myform.topicList"
                  :key="index"
                  closable
                  @close="removeTopic(topic)"
                  class="topic-tag"
                >
                  #{{ topic.name }}
                </el-tag>
              </div>
              <el-button 
                type="primary" 
                plain 
                @click="openTopicDialog()"
                class="select-topic-btn"
              >
                添加话题
              </el-button>
            </div>
          </div>

          <!-- 添加话题弹窗 -->
          <TopicSelectDialog
            v-model="topicDialogVisible"
            @confirm="confirmTopicSelection"
          />

          <!-- 定时发布 -->
          <div class="schedule-section">
            <h3>定时发布 <el-date-picker
                  v-model="myform.publishTime"
                  type="datetime"
                  placeholder="请选择发布时间"
                  :default-time="defaultTime"
                /></h3>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <el-button size="normal" @click="cancelPublish()">取消</el-button>
            <el-button size="normal" type="primary" @click="confirmPublish">发布</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Upload, Plus, Close, Folder } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useAccountStore } from '@/stores/account'
import { useAppStore } from '@/stores/app'
import { materialApi } from '@/api/material'
import { getPlatformTag, getPlatformName, getPlatformMap } from '@/utils/map'
import { jobApi } from '@/api/job'


import MaterialSelectDialog from '@/components/dialogs/MaterialSelectDialog.vue'
import AccountSelectDialog from '@/components/dialogs/AccountSelectDialog.vue'
import TopicSelectDialog from '@/components/dialogs/TopicSelectDialog.vue'
// API base URL


const defaultTime = new Date()

// 获取应用状态管理
const appStore = useAppStore()

// 上传相关状态
const uploadOptionsVisible = ref(false)
const materialSelectVisible = ref(false)
const selectedMaterials = ref([])
const materials = computed(() => appStore.materials)

const isUploading = ref(false)


// form
const myform = reactive({
    fileList: [],
    accountList: [],
    topicList:[],
    publishTime: null,
    title: '',
  })

// 账号相关状态
const accountDialogVisible = ref(false)



const getPlatformNameApi = (type) => {
  return getPlatformName(type)
}

// 话题相关状态
const topicDialogVisible = ref(false)




// 删除已上传文件
const removeFile = (tab, index) => {
  // 从文件列表中删除
  myform.fileList.splice(index, 1)
  
  // 更新显示列表
  myform.displayFileList = [...myform.fileList.map(item => ({
    name: item.name,
    url: item.url
  }))]
  
  ElMessage.success('文件删除成功')
}

// 话题相关方法
// 打开添加话题弹窗
const openTopicDialog = () => {
  topicDialogVisible.value = true
}





// 删除话题
const removeTopic = (topic) => {
  const index = myform.topicList.findIndex(t => t.id === topic.id)
  myform.topicList.splice(index, 1)
}

// 确认添加话题
const confirmTopicSelection = (topiclist) => {
  for (let i = 0; i < topiclist.length; i++) {
    const topic = topiclist[i]
    const exists = myform.topicList.some(oldtopic => oldtopic.id === topic.id)
    if (!exists) {
      myform.topicList.push(topic)
    }
  }
  topicDialogVisible.value = false
  ElMessage.success('添加话题完成')
}

// 账号选择相关方法
// 打开账号选择弹窗
const openAccountDialog = () => {
  accountDialogVisible.value = true
}

// 确认账号选择
const confirmAccountSelection = (accountList) => {

  for (let i = 0; i < accountList.length; i++) {
    const account = accountList[i]
    const exists = myform.accountList.some(oldaccount => oldaccount.id === account.id)
    if (!exists) {
      myform.accountList.push(account)
    }
  }
  accountDialogVisible.value = false
}

// 删除选中的账号
const removeAccount = (tab, index) => {
  myform.accountList.splice(index, 1)
}

// 取消发布
const cancelPublish = () => {
  window.location.reload()
}

// 确认发布
const confirmPublish = async () => {
  if(isUploading.value) {
     return ElMessage.error('上传中，请勿重复点击')
  }
  // 数据验证
  if (myform.fileList.length === 0) {
    return ElMessage.error('请选择视频')
  }
  if (myform.accountList.length < 1) {
    return ElMessage.error('请选择账号')
  }
  if (!myform.title.trim()) {
    return ElMessage.error('请输入标题')
  }
  if (myform.topicList.length < 1) {
    return ElMessage.error('请选择话题')
  }
  // 判断发布时间不能小于当前时间
  if (myform.publishTime < new Date()) {
    return ElMessage.error('请选择正确的发布时间')
  }


  const formData = {
    files: myform.fileList,
    accounts: myform.accountList,
    title: myform.title,
    topics: myform.topicList,
    publishTime: myform.publishTime
  }

  isUploading.value = true
  try {
    const response = await jobApi.addOneJob(formData)
    if (response.code !== 200) {
       ElMessage.error(response.msg || '上传失败')
    }
    ElMessage.success('添加成功')
    window.location.reload()
  } catch (error) {
    ElMessage.error('添加失败: ' + (error.msg || '未知错误'))
  } finally {
    isUploading.value = false
  }
}




// 选择素材库
const selectMaterial = async () => {
  uploadOptionsVisible.value = false
  
  // 如果素材库为空，先获取素材数据
  if (materials.value.length === 0) {
    try {
      const response = await materialApi.getAllMaterials()
      if (response.code === 200) {
        appStore.setMaterials(response.data)
      } else {
        ElMessage.error('获取素材列表失败')
        return
      }
    } catch (error) {
      console.error('获取素材列表出错:', error)
      ElMessage.error('获取素材列表失败')
      return
    }
  }
  
  selectedMaterials.value = []
  materialSelectVisible.value = true
}

// 确认素材选择
const confirmMaterialSelection = (materialList) => {
  if (materialList.length < 1) {
    return ElMessage.warning('请选择至少一个素材')
  }
  if (materialList.length > 1) {
    return ElMessage.warning('只能选择一个素材')
  }
  const material = materialList[0]

  const fileInfo = {
    name: material.filename,
    url: materialApi.getMaterialPreviewUrl(material.filepath),
    path: material.filepath,
    size: material.filesize * 1024 * 1024, // 转换为字节
    type: 'video/mp4'
  }
  
  // 检查是否已存在相同文件
  const exists = myform.fileList.some(file => file.path === fileInfo.path)
  if (!exists) {
    myform.fileList.push(fileInfo)
  }

  materialSelectVisible.value = false
  selectedMaterials.value = []
}





</script>

<style lang="scss" scoped>
@use '@/styles/variables.scss' as *;

.publish-center {
  display: flex;
  flex-direction: column;
  height: 100%;
  
  // Tab管理区域
  .tab-management {
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    padding: 15px 20px;
    
    .tab-header {
      display: flex;
      align-items: flex-start;
      gap: 15px;
      
      .tab-list {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        flex: 1;
        min-width: 0;
        
        .tab-item {
           display: flex;
           align-items: center;
           gap: 6px;
           padding: 6px 12px;
           background-color: #f5f7fa;
           border: 1px solid #dcdfe6;
           border-radius: 4px;
           cursor: pointer;
           transition: all 0.3s;
           font-size: 14px;
           height: 32px;
           
           &:hover {
             background-color: #ecf5ff;
             border-color: #b3d8ff;
           }
           
           &.active {
             background-color: #409eff;
             border-color: #409eff;
             color: #fff;
             
             .close-icon {
               color: #fff;
               
               &:hover {
                 background-color: rgba(255, 255, 255, 0.2);
               }
             }
           }
           
           .close-icon {
             padding: 2px;
             border-radius: 2px;
             cursor: pointer;
             transition: background-color 0.3s;
             font-size: 12px;
             
             &:hover {
               background-color: rgba(0, 0, 0, 0.1);
             }
           }
         }
       }
       
      .tab-actions {
        display: flex;
        gap: 10px;
        flex-shrink: 0;
        
        .add-tab-btn,
        .batch-publish-btn {
          display: flex;
          align-items: center;
          gap: 4px;
          height: 32px;
          padding: 6px 12px;
          font-size: 14px;
          white-space: nowrap;
        }
      }
    }
  }
  
  // 批量发布进度对话框样式
  .publish-progress {
    padding: 20px;
    
    .current-publishing {
      margin: 15px 0;
      text-align: center;
      color: #606266;
    }

    .publish-results {
      margin-top: 20px;
      border-top: 1px solid #EBEEF5;
      padding-top: 15px;
      max-height: 300px;
      overflow-y: auto;

      .result-item {
        display: flex;
        align-items: center;
        padding: 8px 0;
        color: #606266;

        .el-icon {
          margin-right: 8px;
        }

        .label {
          margin-right: 10px;
          font-weight: 500;
        }

        .msg {
          color: #909399;
        }

        &.success {
          color: #67C23A;
        }

        &.error {
          color: #F56C6C;
        }

        &.cancelled {
          color: #909399;
        }
      }
    }
  }

  .dialog-footer {
    text-align: right;
  }
  
  // 内容区域
  .publish-content {
    flex: 1;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 20px;
    
    .tab-content-wrapper {
      display: flex;
      justify-content: center;
      
      .tab-content {
        width: 100%;
        max-width: 800px;
        
        h3 {
          font-size: 16px;
          font-weight: 500;
          color: $text-primary;
          margin: 0 0 10px 0;
        }
        
        .upload-section,
        .account-section,
        .platform-section,
        .title-section,
        .topic-section,
        .schedule-section {
          margin-bottom: 30px;
        }
        
        .video-upload {
          width: 100%;
          
          :deep(.el-upload-dragger) {
            width: 100%;
            height: 180px;
          }
        }
        
        .account-input {
          max-width: 400px;
        }
        
        .platform-buttons {
          display: flex;
          gap: 10px;
          flex-wrap: wrap;
          
          .platform-btn {
            min-width: 80px;
          }
        }
        
        .title-input {
          max-width: 600px;
        }
        
        .topic-display {
          display: flex;
          flex-direction: column;
          gap: 12px;
          
          .selected-topics {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            min-height: 32px;
            
            .topic-tag {
              font-size: 14px;
            }
          }
          
          .select-topic-btn {
            align-self: flex-start;
          }
        }
        
        .schedule-controls {
          display: flex;
          flex-direction: column;
          gap: 15px;

          .schedule-settings {
            margin-top: 15px;
            padding: 15px;
            background-color: #f5f7fa;
            border-radius: 4px;

            .schedule-item {
              display: flex;
              align-items: center;
              margin-bottom: 15px;

              &:last-child {
                margin-bottom: 0;
              }

              .label {
                min-width: 120px;
                margin-right: 10px;
              }

              .el-time-select {
                margin-right: 10px;
              }

              .el-button {
                margin-left: 10px;
              }
            }
          }
        }
        

      }
    }
  }
  
  // 已上传文件列表样式
  .uploaded-files {
    margin-top: 20px;
    
    h4 {
      font-size: 16px;
      font-weight: 500;
      margin-bottom: 12px;
      color: #303133;
    }
    
    .file-list {
      display: flex;
      flex-direction: column;
      gap: 10px;
      
      .file-item {
        display: flex;
        align-items: center;
        padding: 10px 15px;
        background-color: #f5f7fa;
        border-radius: 4px;
        
        .el-link {
          margin-right: 10px;
          max-width: 300px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .file-size {
          color: #909399;
          font-size: 13px;
          margin-right: auto;
        }
      }
    }
  }
  
  // 添加话题弹窗样式
  .topic-dialog {
    .topic-dialog-content {
      .custom-topic-input {
        display: flex;
        gap: 12px;
        margin-bottom: 24px;
        
        .custom-input {
          flex: 1;
        }
      }
      
      .recommended-topics {
        h4 {
          margin: 0 0 16px 0;
          font-size: 16px;
          font-weight: 500;
          color: #303133;
        }
        
        .topic-grid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
          gap: 12px;
          
          .topic-btn {
            height: 36px;
            font-size: 14px;
            border-radius: 6px;
            min-width: 100px;
            padding: 0 12px;
            white-space: nowrap;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
            
            &.el-button--primary {
              background-color: #409eff;
              border-color: #409eff;
              color: white;
            }
          }
        }
      }
    }
    
    .dialog-footer {
      display: flex;
      justify-content: flex-end;
      gap: 12px;
    }
  }
}
</style>
